package com.zhentao.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhentao.aop.MyLog;
import com.zhentao.domain.*;
import com.zhentao.domain.dto.*;
import com.zhentao.result.Result;
import com.zhentao.service.*;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 考试信息控制层
 * */
@RestController
@RequestMapping("/paper")
public class ExaminationInformationController {

    @Resource
    private SExaminationInformationService examinationInformationService;

    @Resource
    private TUserService tUserService;

    @Resource
    private SSubjectService subjectService;

    @Resource
    private SLevelService levelService;

    @Resource
    private STestPaperService sTestPaperService;

    @Resource
    private SLearningProgressService learningProgressService;

    @Resource
    private SClassService classService;

    @Resource
    private SRetakesInfoService retakesInfoService;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Resource
    private SAnswerService answerService;

    //获取管理员和老师信息
    @PostMapping("/getAdminAndTeacherInfo")
    public Result getAdminAndTeacherInfo() {
        return tUserService.getAdminAndTeacherInfo();
    }

    //获取考试信息
    @PostMapping("/getExaminationInfoList")
    public Result getExaminationInfoList(@RequestBody SExaminationInformationDto dto) {
        return examinationInformationService.getExaminationInfoList(dto);
    }

    //添加考试信息
    @MyLog(title = "试卷管理",content = "添加考试信息")
    @PostMapping("/addExaminationInformation")
    public Result addExaminationInformation(@RequestBody SExaminationInformation examinationInformation) {
        return examinationInformationService.addExaminationInformation(examinationInformation);
    }

    //添加考试信息（自己选题）
    @MyLog(title = "试卷管理",content = "添加考试信息（自己选题）")
    @PostMapping("/addExaminationInformationBySelf")
    public Result addExaminationInformationBySelf(@RequestBody AdSExaminationInformation adSExaminationInformation) {
        return examinationInformationService.addExaminationInformationBySelf(adSExaminationInformation);
    }

    //根据考试信息id查找考试信息
    @GetMapping("/getExaminationInfoById/{id}")
    public Result getExaminationInfoById(@PathVariable Integer id) {
        return examinationInformationService.getExaminationInfoById(id);
    }

    //根据考试信息id删除考试信息
    @MyLog(title = "试卷管理",content = "根据考试信息id删除考试信息")
    @PostMapping("/delExaminationInfoById")
    public Result delExaminationInfoById(@RequestBody Integer[] id) {
            for (Integer i : id){
                SExaminationInformation byId = this.examinationInformationService.getById(i);
                ListOperations<String, String> stringObjectListOperations = redisTemplate.opsForList();
                stringObjectListOperations.remove("examinationInfo",0,byId.getId()+"_"+byId.getBeginTime()+"_"+byId.getEndTime()+"_"+byId.getState());
                this.sTestPaperService.remove(Wrappers.<STestPaper>lambdaQuery().eq(STestPaper::getTestinfoId,i));
                this.retakesInfoService.remove(Wrappers.<SRetakesInfo>lambdaQuery().eq(SRetakesInfo::getExaminationId,i));
                this.answerService.remove(Wrappers.<SAnswer>lambdaQuery().eq(SAnswer::getTestinfoId,i));
            }
        boolean b = examinationInformationService.removeBatchByIds(Arrays.asList(id));
            return Result.OK();
    }


    //导出考试信息excel
    @MyLog(title = "试卷管理",content = "导出考试信息excel")
    @GetMapping("/exportFile")
    public void export(HttpServletResponse response) throws IOException {
        List<SExaminationInformationExport> list = examinationInformationService.getSExaminationInformationExport();
        response.setContentType("application/vnd.openxmlformats-officedocument,spreadsheetml,sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("考试信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SExaminationInformationExport.class).sheet("考试信息").doWrite(list);
    }

    //修改考试信息
    @MyLog(title = "试卷管理",content = "修改考试信息")
    @PostMapping("/updateExaminationInformation")
    public Result updateExaminationInformation(@RequestBody SExaminationInformation sExaminationInformation){
        return examinationInformationService.updateExaminationInformation(sExaminationInformation);
    }

    //根据考试信息id查看这场考试的试卷内容
    @GetMapping("/getTestPaper/{id}")
    public Result getTestPaper(@PathVariable("id") Integer id){
        return examinationInformationService.getTestPaper(id);
    }

    //获取课程信息
    @GetMapping("/getSubjectList")
    public Result getSubjectList() {
        List<LevelSubjectDto> list=levelService.getSubjectList();
        return Result.OK(list);
    }
    //根据学习阶段查询单元信息
    @GetMapping("/getSubjectById/{id}")
    public Result getSubjectById(@PathVariable("id")Integer id) {
        List<SSubject> list = subjectService.list(Wrappers.<SSubject>lambdaQuery().eq(SSubject::getLpId, id));
        return Result.OK(list);
    }
    //查询阶段信息
    @PostMapping("/getLevelList")
    public Result getLevelList() {
        List<SLevel> list = levelService.list();
        return Result.OK(list);
    }
    //回显阶段信息
    @GetMapping("/getLevelById/{id}")
    public Result getLevelById(@PathVariable("id")Integer id) {
        QueryWrapper<SSubject> queryWrapper = new QueryWrapper<>();
        SSubject subject = subjectService.getOne(queryWrapper.lambda().eq(SSubject::getId,id));
        return Result.OK(subject);
    }

    //删除单个考试试卷中对应的题目
    @MyLog(title = "试卷管理",content = "删除单个考试试卷中对应的题目")
    @GetMapping("/delQuestionById/{qid}/{eid}")
    public Result delQuestion(@PathVariable("qid") Integer qid,@PathVariable("eid") Integer eid) {
        return sTestPaperService.delQuestionById(qid,eid);
    }

    //精准添加考试题目
    @MyLog(title = "试卷管理",content = "精准添加考试题目")
    @GetMapping("/addQuestion/{qid}/{eid}")
    public Result addQuestion(@PathVariable("qid") Integer[] qid,@PathVariable("eid") Integer eid) {
        return sTestPaperService.addQuestion(qid,eid);
    }

    //根据阶段信息查询学习阶段
    @GetMapping("/getLPById/{id}")
    public Result getLPById(@PathVariable("id")Integer id) {
        List<SLearningProgress> list = learningProgressService.list(Wrappers.<SLearningProgress>lambdaQuery().eq(SLearningProgress::getLevelId, id));
        return Result.OK(list);
    }

    //查找所有的班级信息
    @GetMapping("/getClassList")
    public Result getClassList() {
        List<SClass> list = classService.list();
        return Result.OK(list);
    }

    //发布教学周期日考
    @MyLog(title = "试卷管理",content = "发布教学周期日考")
    @PostMapping("/addDailyExams")
    public Result addDailyExams(@RequestBody CycleDailyExams cycleDailyExams) {
        return examinationInformationService.addDailyExams(cycleDailyExams);
    }



    //根据讲师id查找该讲师带班的对应考试
    @PostMapping("/getExaminationInfoListByTeacherId/{tid}")
    public Result getExaminationInfoListByTeacherId(@PathVariable("tid") Integer tid,@RequestBody SExaminationInformationDto dto) {
        return examinationInformationService.getExaminationInfoListByTeacherId(tid,dto);
    }
    //管理员同意讲师发布试卷
    @GetMapping("/passExamination/{id}")
    @MyLog(title = "试卷管理",content = "管理员同意讲师发布试卷")
    public Result passExamination(@PathVariable("id")Integer id){
        SExaminationInformation examinationInformation = examinationInformationService.getById(id);
        Date date = new Date();
        //判断当前时间在开始时间之后结束时间之前该试卷状态修改为考试中
        if (date.compareTo(examinationInformation.getBeginTime())>0&&date.compareTo(examinationInformation.getEndTime())<0){
            examinationInformation.setState(1);
            redisTemplate.opsForList().leftPush("examinationInfo",examinationInformation.getId()+"_"+examinationInformation.getBeginTime()+"_"+examinationInformation.getEndTime()+"_"+1);
        }else if (date.compareTo(examinationInformation.getBeginTime())<0){
            //判断当前时间在开始时间之前该试卷状态修改为待开始
            examinationInformation.setState(0);
            redisTemplate.opsForList().leftPush("examinationInfo",examinationInformation.getId()+"_"+examinationInformation.getBeginTime()+"_"+examinationInformation.getEndTime()+"_"+0);
        }else {
            //反之这说明考试已经结束
            examinationInformation.setState(2);
        }
        examinationInformationService.updateById(examinationInformation);
        return Result.OK("审批通过");
    }
    //管理员驳回讲师发布试卷
    @GetMapping("/rejectExamination/{id}/{backCause}")
    @MyLog(title = "试卷管理",content = "管理员驳回讲师发布试卷")
    public Result rejectExamination(@PathVariable("id")Integer id,@PathVariable("backCause")String backCause){
        SExaminationInformation examinationInformation = examinationInformationService.getById(id);
        examinationInformation.setState(4);
        examinationInformation.setBackCause(backCause);
        examinationInformationService.updateById(examinationInformation);
        return Result.OK("审批驳回");
    }
}
